'''
Author: your name
Date: 2020-10-29 14:23:10
LastEditTime: 2020-10-29 14:44:27
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \python-study\博客学习\深入\上下文管理.py
'''
class VOW(object):
    def __init__(self, text):
        self.text = text
    # 当进入程序块时，会自动启动该方法，自动进入上下文管理
    def __enter__(self):
        self.text = "I say: " + self.text    # add prefix
        return self                          # note: return an object
    # 当程序块完成时，会自动调用该方法自动完成
    def __exit__(self,exc_type,exc_value,traceback):
        self.text = self.text + "!"          # add suffix

def withoutContext():
    f = open("new.txt", "w")
    print(f.closed)               # whether the file is open
    f.write("Hello World!")
    f.close()
    print(f.closed)

def withContext():
    with open("new.txt", "w") as f:
        print(f.closed)
        f.write("Hello World!")
    print(f.closed)

if __name__=="__main__":
    withoutContext();
    withContext();
    with VOW("I'm fine") as myvow:
        print(myvow.text)

    print(myvow.text)